/*
 *   验证码倒计时和获取，参数列表：
 *   ele: 按钮的DOM对象
 *   opt: -url -请求的url [字符串]
 *        -timeout -重新发送倒计时  -[int](秒)   -默认值60
 *        -phone -手机号表单验证
 *
 */
function Authhandle(ele, opt) {
    var clicked = false;
    this.obj = ele;
    this.url = opt.url;
    this.timeout = (opt.timeout != 'undefined' && opt.timeout > 0) ? opt.timeout : 60;
    this.count = this.timeout;
    this.phone = opt.phone;
    this.timer;
    this.init();
};

Authhandle.prototype = {
    getClick: function() {
        return clicked;
    },
    setClick: function(clicked) {
        clicked = clicked;
    },
    setRemainTime: function() {
        if (this.count <= 0) {
            clearInterval(this.timer); //停止计时器  
            this.clicked = false;
            this.obj.text('重新发送');
        } else {
            this.count--;
            this.clicked = true;
            this.obj.text(this.count + 's后重发');
        }
    },
    sendMessage: function() {
        if (!this.checkPhone) {
            alert('手机号格式不正确！');
            return;
        }
        if (!this.checkTime()) {
            return;
        }
        var data = {
            phone: this.phone.val()
        };
        /*请求验证码*/
        Ajax({
            url: this.url,
            data: data,
            call1: this.getAuth.bind(this),
            call2: this.getFail.bind(this)
        });
    },
    checkPhone: function() {
        return (this.phone.search(/^1[34578]\d{9}$/) === -1) ? false : true;
    },
    checkTime: function() {
        var now = new Date().getTime();
        var last = localStorage.lastTime;
        var ts = now - last;
        var ss = parseInt(ts / 1000);
        if (ss < this.timeout) {
            this.count = this.timeout - ss;
            clearInterval(this.timer);
            this.timer = setInterval(this.setRemainTime.bind(this), 1000);
            return false;
        }
        return true;
    },
    /*处理验证码返回的请求*/
    getAuth: function(json) {
        this.clicked = true;
        this.count = this.timeout;
        localStorage.lastTime = new Date().getTime();
        clearInterval(this.timer);
        this.timer = setInterval(this.setRemainTime.bind(this), 1000);
    },
    /*验证码发送失败*/
    getFail: function(json) {
        clicked = false;
    },
    init: function() {
        this.checkTime();
        var _this = this;
        this.obj.click(function() {
            if (_this.getClick()) {
                return;
            };
            _this.setClick(true);
            _this.sendMessage();
        });
    }
};
